function Show-Banner {
    Write-Host ""
    Write-Host "╔════════════════════════════════════════════════════════╗" -ForegroundColor Blue
    Write-Host "║                                                        ║" -ForegroundColor Blue
    Write-Host "║           Docker 完全清理脚本 v1.0                     ║" -ForegroundColor Blue
    Write-Host "║           (Windows PowerShell 版)                      ║" -ForegroundColor Blue
    Write-Host "║                                                        ║" -ForegroundColor Blue
    Write-Host "║  本脚本将执行以下操作：                                ║" -ForegroundColor Blue
    Write-Host "║  [1] 停止并删除所有容器（运行中 + 停止的）             ║" -ForegroundColor Blue
    Write-Host "║  [2] 删除所有镜像                                      ║" -ForegroundColor Blue
    Write-Host "║  [3] 清理未使用的网络                                  ║" -ForegroundColor Blue
    Write-Host "║  [4] 删除所有卷                                        ║" -ForegroundColor Blue
    Write-Host "║                                                        ║" -ForegroundColor Blue
    Write-Host "║  ⚠️  警告：此操作不可逆，将清空所有 Docker 数据！      ║" -ForegroundColor Red
    Write-Host "║                                                        ║" -ForegroundColor Blue
    Write-Host "╚════════════════════════════════════════════════════════╝" -ForegroundColor Blue
    Write-Host ""
}

function Test-Administrator {
    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

function Test-Docker {
    try {
        $null = Get-Command docker -ErrorAction Stop
        Write-Host "✓ Docker 已安装" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "错误：未检测到 Docker，请先安装 Docker Desktop" -ForegroundColor Red
        return $false
    }
}

function Remove-AllContainers {
    Write-Host "`n[步骤 1/4] 正在处理容器..." -ForegroundColor Blue
    
    try {
        $containers = docker ps -aq 2>$null
        
        if (-not $containers) {
            Write-Host "  → 没有需要删除的容器" -ForegroundColor Yellow
        }
        else {
            $containerCount = ($containers | Measure-Object).Count
            Write-Host "  → 发现 $containerCount 个容器" -ForegroundColor Yellow
            Write-Host "  → 正在停止所有运行中的容器..."
            
            $runningContainers = docker ps -q 2>$null
            if ($runningContainers) {
                docker stop $runningContainers 2>$null | Out-Null
            }
            
            Write-Host "  → 正在删除所有容器..."
            docker rm -f $containers 2>$null | Out-Null
            
            Write-Host "  ✓ 已删除 $containerCount 个容器" -ForegroundColor Green
        }
    }
    catch {
        Write-Host "  警告：容器清理过程中出现问题: $($_.Exception.Message)" -ForegroundColor Yellow
    }
}

function Remove-AllImages {
    Write-Host "`n[步骤 2/4] 正在处理镜像..." -ForegroundColor Blue
    
    try {
        $images = docker images -q 2>$null
        
        if (-not $images) {
            Write-Host "  → 没有需要删除的镜像" -ForegroundColor Yellow
        }
        else {
            $imageCount = ($images | Measure-Object).Count
            Write-Host "  → 发现 $imageCount 个镜像" -ForegroundColor Yellow
            Write-Host "  → 正在删除所有镜像..."
            docker rmi -f $images 2>$null | Out-Null
            
            Write-Host "  ✓ 已删除 $imageCount 个镜像" -ForegroundColor Green
        }
    }
    catch {
        Write-Host "  警告：镜像清理过程中出现问题: $($_.Exception.Message)" -ForegroundColor Yellow
    }
}

function Remove-UnusedNetworks {
    Write-Host "`n[步骤 3/4] 正在清理网络..." -ForegroundColor Blue
    
    try {
        Write-Host "  → 正在清理未使用的网络..."
        $result = docker network prune -f 2>&1
        
        if ($result -match "Total reclaimed space: 0B") {
            Write-Host "  → 没有需要清理的网络" -ForegroundColor Yellow
        }
        else {
            Write-Host "  ✓ 网络清理完成" -ForegroundColor Green
            $deletedNetworks = $result | Select-String "Deleted Networks:"
            if ($deletedNetworks) {
                Write-Host "  $deletedNetworks"
            }
        }
    }
    catch {
        Write-Host "  警告：网络清理过程中出现问题: $($_.Exception.Message)" -ForegroundColor Yellow
    }
}

function Remove-AllVolumes {
    Write-Host "`n[步骤 4/4] 正在处理卷..." -ForegroundColor Blue
    
    try {
        $volumes = docker volume ls -q 2>$null
        
        if (-not $volumes) {
            Write-Host "  → 没有需要删除的卷" -ForegroundColor Yellow
        }
        else {
            $volumeCount = ($volumes | Measure-Object).Count
            Write-Host "  → 发现 $volumeCount 个卷" -ForegroundColor Yellow
            Write-Host "  → 正在删除所有卷..."
            docker volume rm $volumes 2>$null | Out-Null
            
            Write-Host "  ✓ 已删除 $volumeCount 个卷" -ForegroundColor Green
        }
    }
    catch {
        Write-Host "  警告：卷清理过程中出现问题: $($_.Exception.Message)" -ForegroundColor Yellow
    }
}

function Show-Summary {
    Write-Host ""
    Write-Host "╔════════════════════════════════════════╗" -ForegroundColor Green
    Write-Host "║                                        ║" -ForegroundColor Green
    Write-Host "║     🎉 Docker 清理完成！               ║" -ForegroundColor Green
    Write-Host "║                                        ║" -ForegroundColor Green
    Write-Host "║     Docker 已恢复到初始状态            ║" -ForegroundColor Green
    Write-Host "║                                        ║" -ForegroundColor Green
    Write-Host "╚════════════════════════════════════════╝" -ForegroundColor Green
    
    Write-Host "`n当前 Docker 状态：" -ForegroundColor Blue
    
    try {
        $containerCount = (docker ps -a 2>$null | Measure-Object -Line).Lines - 1
        $imageCount = (docker images 2>$null | Measure-Object -Line).Lines - 1
        $networkCount = (docker network ls 2>$null | Measure-Object -Line).Lines - 1
        $volumeCount = (docker volume ls 2>$null | Measure-Object -Line).Lines - 1
        
        Write-Host "  容器数量: $containerCount (应为0)"
        Write-Host "  镜像数量: $imageCount (应为0)"
        Write-Host "  网络数量: $networkCount (仅保留默认网络)"
        Write-Host "  卷数量:   $volumeCount (应为0)"
        
        Write-Host "`nDocker 磁盘使用情况：" -ForegroundColor Blue
        docker system df
    }
    catch {
        Write-Host "  无法获取统计信息: $($_.Exception.Message)" -ForegroundColor Yellow
    }
}

function Clean-AllDocker {
    param([switch]$SkipConfirm)
    
    Show-Banner
    
    if (-not (Test-Administrator)) {
        Write-Host "提示：建议使用管理员权限运行此脚本" -ForegroundColor Yellow
        Write-Host "如遇到权限问题，请右键选择 '以管理员身份运行' PowerShell" -ForegroundColor Yellow
        Write-Host ""
    }
    
    if (-not (Test-Docker)) {
        return
    }
    
    Write-Host ""
    Write-Host "⚠️  警告：即将清空所有 Docker 数据，此操作不可恢复！" -ForegroundColor Red
    Write-Host ""
    
    Write-Host "`n开始清理 Docker...`n" -ForegroundColor Blue
    
    Remove-AllContainers
    Remove-AllImages
    Remove-UnusedNetworks
    Remove-AllVolumes
    
    Write-Host "`n[额外清理] 正在执行系统级清理..." -ForegroundColor Blue
    try {
        docker system prune -a -f --volumes 2>$null | Out-Null
        Write-Host "  ✓ 系统清理完成" -ForegroundColor Green
    }
    catch {
        Write-Host "  警告：系统清理过程中出现问题" -ForegroundColor Yellow
    }
    
    Show-Summary
}

if ($MyInvocation.InvocationName -ne '.') {
    foreach ($arg in $args) {
        if ($arg -eq '-Help' -or $arg -eq '-h' -or $arg -eq '--help') {
            Write-Host @"
使用方法: .\docker_clean_all.ps1 [-Help]
  -Help           显示此帮助信息

在线执行示例:
  irm <url> | iex; Clean-AllDocker
"@
            exit 0
        }
    }
    Clean-AllDocker
}
